package com.dreamoo.common.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.*;

/**
 * @author 山顶洞人郑某
 * @className ThreadPoolConfig.java 线程池配置 （利用TTL）
 * @date 2025 05 06
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public Executor threadPoolExecutor() {
       ThreadPoolExecutor threadPoolExecutor =  new ThreadPoolExecutor(
               Runtime.getRuntime().availableProcessors() +1,
               maximumPoolSize(),
               60,
               TimeUnit.SECONDS,
               new ArrayBlockingQueue<>(600)
       );
        return TtlExecutors.getTtlExecutor(threadPoolExecutor);
    }

    private static Integer maximumPoolSize() {
        return new BigDecimal(Runtime.getRuntime().availableProcessors())
                .divide(new BigDecimal("0.2"), 0, RoundingMode.HALF_UP).intValue();
    }
}
